/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.tousu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import vip.xiaonuo.biz.modular.tousu.entity.Tousu;
import vip.xiaonuo.biz.modular.tousu.mapper.TousuMapper;
import vip.xiaonuo.biz.modular.tousu.param.TousuAddParam;
import vip.xiaonuo.biz.modular.tousu.param.TousuEditParam;
import vip.xiaonuo.biz.modular.tousu.param.TousuIdParam;
import vip.xiaonuo.biz.modular.tousu.param.TousuPageParam;
import vip.xiaonuo.biz.modular.tousu.service.TousuService;

import vip.xiaonuo.common.util.CommonDownloadUtil;
import vip.xiaonuo.common.util.CommonResponseUtil;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 投诉信息表Service接口实现类
 *
 * @author damionew
 * @date  2025/07/08 15:47
 **/
@Slf4j
@Service
public class TousuServiceImpl extends ServiceImpl<TousuMapper, Tousu> implements TousuService {

    @Autowired
    TousuMapper tousuMapper;

    @Override
    public Page<Tousu> page(TousuPageParam tousuPageParam) {
        QueryWrapper<Tousu> queryWrapper = new QueryWrapper<Tousu>().checkSqlInjection();
        if(ObjectUtil.isAllNotEmpty(tousuPageParam.getSortField(), tousuPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(tousuPageParam.getSortOrder());
            queryWrapper.orderBy(true, tousuPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(tousuPageParam.getSortField()));
        } else {
        }
        // 添加判断：是否有营商
        String hasBusiness = tousuPageParam.getHasBusiness();
        String dateRange = tousuPageParam.getDateRange();
        String complainantNumber = tousuPageParam.getComplainantNumber();
        String issuedNumber = tousuPageParam.getIssuedNumber();
        if (hasBusiness != null && !hasBusiness.isEmpty()) {
            if (hasBusiness.equals("0")) {
                // 没有营商
                queryWrapper.lambda()
                        .isNull(Tousu::getAccusedProvince)
                        .or()
                        .eq(Tousu::getAccusedProvince, "");;
            }else if (hasBusiness.equals("1")) {
                // 有营商
                queryWrapper.lambda()
                        .isNotNull(Tousu::getAccusedProvince)
                        .ne(Tousu::getAccusedProvince, "");;
            }
        }
        if (dateRange != null && !dateRange.isEmpty()) {
            if (dateRange.equals("3")) {
                // 3天内
                queryWrapper.lambda()
                       .ge(Tousu::getComplaintTime, DateUtil.offsetDay(new Date(), -3));
            }else if (dateRange.equals("7")) {
                // 7天内
                queryWrapper.lambda()
                      .ge(Tousu::getComplaintTime, DateUtil.offsetDay(new Date(), -7));
            }else if (dateRange.equals("15")) {
                // 15天内
                queryWrapper.lambda()
                     .ge(Tousu::getComplaintTime, DateUtil.offsetDay(new Date(), -15));
            }
        }
        if (complainantNumber!= null &&!complainantNumber.isEmpty()) {
            queryWrapper.lambda()
                    .like(Tousu::getComplainantNumber, complainantNumber);
        }
        if (issuedNumber!= null &&!issuedNumber.isEmpty()) {
            queryWrapper.lambda()
                    .like(Tousu::getIssuedNumber, issuedNumber);
        }
        queryWrapper.lambda().orderByDesc(Tousu::getComplaintTime);
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(TousuAddParam tousuAddParam) {
        Tousu tousu = BeanUtil.toBean(tousuAddParam, Tousu.class);
        this.save(tousu);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(TousuEditParam tousuEditParam) {
        Tousu tousu = this.queryEntity(tousuEditParam.getId());
        BeanUtil.copyProperties(tousuEditParam, tousu);
        this.updateById(tousu);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(int id) {
        // 执行删除
        this.removeById(id);
    }

    @Override
    public Tousu detail(TousuIdParam tousuIdParam) {
        return this.queryEntity(tousuIdParam.getId());
    }

    @Override
    public Tousu queryEntity(String id) {
        Tousu tousu = this.getById(id);
        if(ObjectUtil.isEmpty(tousu)) {
            throw new CommonException("投诉信息表不存在，id值为：{}", id);
        }
        return tousu;
    }

    @Override
    public void downloadImportTemplate(HttpServletResponse response) throws IOException {
       File tempFile = null;
       try {
         List<TousuEditParam> dataList = CollectionUtil.newArrayList();
         String fileName = "投诉信息表导入模板_" + DateUtil.format(DateTime.now(), DatePattern.PURE_DATETIME_PATTERN) + ".xlsx";
         tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);
         EasyExcel.write(tempFile.getPath(), TousuEditParam.class).sheet("投诉信息表").doWrite(dataList);
         CommonDownloadUtil.download(tempFile, response);
       } catch (Exception e) {
         log.error(">>> 投诉信息表导入模板下载失败：", e);
         CommonResponseUtil.renderError(response, "投诉信息表导入模板下载失败");
       } finally {
         FileUtil.del(tempFile);
       }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject importData(MultipartFile file) {
        try {
            int successCount = 0;
            int errorCount = 0;
            JSONArray errorDetail = JSONUtil.createArray();
            // 创建临时文件
            File tempFile = FileUtil.writeBytes(file.getBytes(), FileUtil.file(FileUtil.getTmpDir() +
                    FileUtil.FILE_SEPARATOR + "tousuImportTemplate.xlsx"));
            // 读取excel
            List<TousuEditParam> tousuEditParamList =  EasyExcel.read(tempFile).head(TousuEditParam.class).sheet()
                    .headRowNumber(1).doReadSync();
            List<Tousu> allDataList = this.list();
            for (int i = 0; i < tousuEditParamList.size(); i++) {
                JSONObject jsonObject = this.doImport(allDataList, tousuEditParamList.get(i), i);
                if(jsonObject.getBool("success")) {
                    successCount += 1;
                } else {
                    errorCount += 1;
                    errorDetail.add(jsonObject);
                }
            }
            return JSONUtil.createObj()
                    .set("totalCount", tousuEditParamList.size())
                    .set("successCount", successCount)
                    .set("errorCount", errorCount)
                    .set("errorDetail", errorDetail);
        } catch (Exception e) {
            log.error(">>> 投诉信息表导入失败：", e);
            throw new CommonException("投诉信息表导入失败");
        }
    }

    public JSONObject doImport(List<Tousu> allDataList, TousuEditParam tousuEditParam, int i) {
        String id = tousuEditParam.getId();
        if(ObjectUtil.hasEmpty(id)) {
            return JSONUtil.createObj().set("index", i + 1).set("success", false).set("msg", "必填字段存在空值");
        } else {
            try {
                int index = CollStreamUtil.toList(allDataList, Tousu::getId).indexOf(tousuEditParam.getId());
                Tousu tousu;
                boolean isAdd = false;
                if(index == -1) {
                    isAdd = true;
                    tousu = new Tousu();
                } else {
                    tousu = allDataList.get(index);
                }
                BeanUtil.copyProperties(tousuEditParam, tousu);
                if(isAdd) {
                    allDataList.add(tousu);
                } else {
                    allDataList.remove(index);
                    allDataList.add(index, tousu);
                }
                this.saveOrUpdate(tousu);
                return JSONUtil.createObj().set("success", true);
            } catch (Exception e) {
              log.error(">>> 数据导入异常：", e);
              return JSONUtil.createObj().set("success", false).set("index", i + 1).set("msg", "数据导入异常");
            }
        }
    }

    @Override
    public void exportData(List<TousuIdParam> tousuIdParamList, HttpServletResponse response) throws IOException {
       File tempFile = null;
       try {
         List<TousuEditParam> dataList;
         if(ObjectUtil.isNotEmpty(tousuIdParamList)) {
            List<String> idList = CollStreamUtil.toList(tousuIdParamList, TousuIdParam::getId);
            dataList = BeanUtil.copyToList(this.listByIds(idList), TousuEditParam.class);
         } else {
            dataList = BeanUtil.copyToList(this.list(), TousuEditParam.class);
         }
         String fileName = "投诉信息表_" + DateUtil.format(DateTime.now(), DatePattern.PURE_DATETIME_PATTERN) + ".xlsx";
         tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);
         EasyExcel.write(tempFile.getPath(), TousuEditParam.class).sheet("投诉信息表").doWrite(dataList);
         CommonDownloadUtil.download(tempFile, response);
       } catch (Exception e) {
         log.error(">>> 投诉信息表导出失败：", e);
         CommonResponseUtil.renderError(response, "投诉信息表导出失败");
       } finally {
         FileUtil.del(tempFile);
       }
    }

    @Override
    public int getLastDapanCount() {
        // 获取昨天年月日，格式为yyyyMMdd
        String recordDate = DateUtil.yesterday().toString(DatePattern.NORM_DATE_PATTERN);
        return tousuMapper.getLastDapanCount(recordDate);
    }
    @Override
    public float getLastDapanRate() {
        String lastDay1 = DateUtil.offsetDay(new Date(), -1).toString(DatePattern.NORM_DATE_PATTERN);
        // 前天年月日，格式为yyyy-MM-dd
        String lastDay2 =DateUtil.offsetDay(new Date(), -2).toString(DatePattern.NORM_DATE_PATTERN);
        int lastDayDapanCount1 = tousuMapper.getLastDapanCount(lastDay1);
        int lastDayDapanCount2 = tousuMapper.getLastDapanCount(lastDay2);
        // 计算同比
        if(lastDayDapanCount2 != 0) {
            BigDecimal lastDayTousuCountBigDecimal = new BigDecimal(lastDayDapanCount1);
            BigDecimal lastlastDayTousuCountBigDecimal = new BigDecimal(lastDayDapanCount2);
            // 同比 = （昨天投诉量 - 前天投诉量）/ 前天投诉量 * 100%
            float result = lastDayTousuCountBigDecimal.subtract(lastlastDayTousuCountBigDecimal).divide(lastlastDayTousuCountBigDecimal, 2, BigDecimal.ROUND_HALF_UP).floatValue();
            return result;
        }
        return 0;
    }

    @Override
    public int getLastTousuCount() {
        // 获取昨天年月日，格式为yyyyMMdd
        String recordDate = DateUtil.yesterday().toString(DatePattern.NORM_DATE_PATTERN);
        return tousuMapper.getLastTousuCount(recordDate);
    }

    @Override
    public float getLastTousuRate() {
        // 昨天年月日，格式为yyyy-MM-dd
        String lastDay1 = DateUtil.offsetDay(new Date(), -1).toString(DatePattern.NORM_DATE_PATTERN);
        // 前天年月日，格式为yyyy-MM-dd
        String lastDay2 =DateUtil.offsetDay(new Date(), -2).toString(DatePattern.NORM_DATE_PATTERN);
        // 昨日投诉同比
        int lastDayTousuCount = tousuMapper.getTousuCountByDay(lastDay1);
        int lastlastDayTousuCount = tousuMapper.getTousuCountByDay(lastDay2);
        // 计算同比
        if(lastlastDayTousuCount != 0) {
            BigDecimal lastDayTousuCountBigDecimal = new BigDecimal(lastDayTousuCount);
            BigDecimal lastlastDayTousuCountBigDecimal = new BigDecimal(lastlastDayTousuCount);
            // 同比 = （昨天投诉量 - 前天投诉量）/ 前天投诉量 * 100%
            float result = lastDayTousuCountBigDecimal.subtract(lastlastDayTousuCountBigDecimal).divide(lastlastDayTousuCountBigDecimal, 2, BigDecimal.ROUND_HALF_UP).floatValue();
            return result;
        }
        return 0;
    }

    @Override
    public int getLastBelongTousuCount() {
        // 昨天年月日，格式为yyyy-MM-dd
        String lastDay1 = DateUtil.offsetDay(new Date(), -1).toString(DatePattern.NORM_DATE_PATTERN);
        // 昨日投诉量
        int lastDayTousuCount = tousuMapper.getLastBelongTousuCount(lastDay1);
        return lastDayTousuCount;
    }

    @Override
    public float getLastBelongTousuRate() {
        // 昨天年月日，格式为yyyy-MM-dd
        String lastDay1 = DateUtil.offsetDay(new Date(), -1).toString(DatePattern.NORM_DATE_PATTERN);
        // 前天年月日，格式为yyyy-MM-dd
        String lastDay2 =DateUtil.offsetDay(new Date(), -2).toString(DatePattern.NORM_DATE_PATTERN);
        // 昨日投诉同比
        int lastDayTousuCount = tousuMapper.getBelongTousuCountByDay(lastDay1);
        int lastlastDayTousuCount = tousuMapper.getBelongTousuCountByDay(lastDay2);
        // 计算同比
        if(lastlastDayTousuCount != 0) {
            BigDecimal lastDayTousuCountBigDecimal = new BigDecimal(lastDayTousuCount);
            BigDecimal lastlastDayTousuCountBigDecimal = new BigDecimal(lastlastDayTousuCount);
            float result = lastDayTousuCountBigDecimal.subtract(lastlastDayTousuCountBigDecimal).divide(lastlastDayTousuCountBigDecimal, 2, BigDecimal.ROUND_HALF_UP).floatValue();
            return result;
        }
        return 0;
    }

    @Override
    public int getThisMonthTousuCount() {
        // 获取这个月格式化，yyyy-MM
        String recordDate = DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN);
        // 昨日投诉量
        int lastDayTousuCount = tousuMapper.getThisMonthTousuCountByMonth(recordDate);
        return lastDayTousuCount;
    }

    @Override
    public float getThisMonthTousuRate() {
        // 获取这个月格式化，yyyy-MM
        String thisMonth = DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN);
        // 获取上个月格式化，yyyy-MM
        String lastMonth = DateUtil.offsetMonth(new Date(), -1).toString(DatePattern.NORM_MONTH_PATTERN);
        // 昨日投诉同比
        int lastDayTousuCount = tousuMapper.getThisMonthTousuCountByMonth(thisMonth);
        int lastlastDayTousuCount = tousuMapper.getThisMonthTousuCountByMonth(lastMonth);
        // 计算同比
        if(lastlastDayTousuCount != 0) {
            BigDecimal lastDayTousuCountBigDecimal = new BigDecimal(lastDayTousuCount);
            BigDecimal lastlastDayTousuCountBigDecimal = new BigDecimal(lastlastDayTousuCount);
            float result = lastDayTousuCountBigDecimal.subtract(lastlastDayTousuCountBigDecimal).divide(lastlastDayTousuCountBigDecimal, 2, BigDecimal.ROUND_HALF_UP).floatValue();
            return result;
        }
        return 0;
    }

    @Override
    public int getThisQuarterTousuCount() {
        LocalDate localDate = LocalDate.now();
        Map<String,String> dateRange = calculateQuarterDateRange(localDate);
        String startDate = dateRange.get("startDate");
        String endDate = dateRange.get("endDate");
        int sumV = tousuMapper.getTousuCountByRange(startDate,endDate);
        return sumV;
    }

    @Override
    public float getThisQuarterTousuRate() {
        // 获取今天的日期的LocalDate格式
        LocalDate localDate = LocalDate.now();
        Map<String,String> dateRange = calculateQuarterDateRange(localDate);
        String startDate = dateRange.get("startDate");
        String endDate = dateRange.get("endDate");
        int sumV = tousuMapper.getTousuCountByRange(startDate,endDate);

        Map<String,String> dateRange2 = calculatePreviousQuarterRange(localDate);
        String startDate2 = dateRange2.get("startDate");
        String endDate2 = dateRange2.get("endDate");
        int sumV2 = tousuMapper.getTousuCountByRange(startDate2,endDate2);

        // 计算同比，（sumV-sumV2）/ sumV2 * 100%
        if(sumV2!= 0) {
            BigDecimal sumVBigDecimal = new BigDecimal(sumV);
            BigDecimal sumV2BigDecimal = new BigDecimal(sumV2);
            float result = sumVBigDecimal.subtract(sumV2BigDecimal).divide(sumV2BigDecimal, 2, BigDecimal.ROUND_HALF_UP).floatValue();
            return result;
        }
        return sumV;
    }

    @Override
    public List<Map<String, Integer>> getDapanLineData(String startDate, String endDate) {
        List<Map<String, Integer>> list = tousuMapper.getDapanLineData(startDate, endDate);
        return list;
    }

    @Override
    public List<Map<String, Integer>> getTousuLineData(String startDate, String endDate) {
        List<Map<String, Integer>> list = tousuMapper.getTousuLineData(startDate, endDate);
        return list;
    }
    @Override
    public List<Map<String, String>> getTousuNumberList(String searchKey) {
        LocalDate localDate = LocalDate.now();
        Map<String,String> dateRange = calculateQuarterDateRange(localDate);
        String startDate = dateRange.get("startDate");
        String endDate = dateRange.get("endDate");
        Map<String,String> dateRange2 = calculatePreviousQuarterRange(localDate);
        String startDate2 = dateRange2.get("startDate");
        String endDate2 = dateRange2.get("endDate");
        List<Map<String, String>> list = tousuMapper.getTousuNumberList(searchKey,startDate,endDate,startDate2,endDate2);
        return list;
    }

    @Override
    public void updateIssuedNumber(TousuEditParam tousuEditParam) {
        // 根据id，更新issuedNumber
        tousuMapper.updateIssuedNumberById(tousuEditParam);
    }

    @Override
    public void updateBelongCustomer(TousuEditParam tousuEditParam) {
        // 根据id，更新issuedNumber
        tousuMapper.updateBelongCustomerById(tousuEditParam);
    }

    @Override
    public void updateBelongArea(TousuEditParam tousuEditParam) {
        // 根据id，更新issuedNumber
        tousuMapper.updateBelongAreaById(tousuEditParam);
    }

    @Override
    public void tousuUpdateForm(TousuEditParam tousuEditParam) {
        // 根据id，更新issuedNumber
        tousuMapper.tousuUpdateForm(tousuEditParam);
    }

    public static Map<String, String> calculateQuarterDateRange(LocalDate inputDate) {
        Map<String, String> result = new HashMap<>();

        // 获取输入日期的年、月、日
        int year = inputDate.getYear();
        int month = inputDate.getMonthValue();
        int day = inputDate.getDayOfMonth();

        // 确定原始季度（1-4）
        int originalQuarter = (month - 1) / 3 + 1;

        // 判断是否需要调整到下一个季度（季度最后一个月的26号及之后）
        boolean needAdjust = (day >= 26) && (month == 3 || month == 6 || month == 9 || month == 12);

        // 计算调整后的季度和年份
        int adjustedQuarter;
        int adjustedYear;

        if (needAdjust) {
            if (originalQuarter == 4) {
                adjustedQuarter = 1;
                adjustedYear = year + 1;
            } else {
                adjustedQuarter = originalQuarter + 1;
                adjustedYear = year;
            }
        } else {
            adjustedQuarter = originalQuarter;
            adjustedYear = year;
        }

        // 计算季度开始日期（上个季度最后一个月的26号）
        LocalDate startDate;
        if (adjustedQuarter == 1) {
            // 第一季度的开始是上一年12月26号
            startDate = LocalDate.of(adjustedYear - 1, 12, 26);
        } else {
            // 其他季度的开始是上个季度最后一个月的26号
            int lastMonthOfPreviousQuarter = (adjustedQuarter - 1) * 3;
            startDate = LocalDate.of(adjustedYear, lastMonthOfPreviousQuarter, 26);
        }

        // 计算季度结束日期（本季度最后一个月的25号）
        int lastMonthOfCurrentQuarter = adjustedQuarter * 3;
        LocalDate endDate = LocalDate.of(adjustedYear, lastMonthOfCurrentQuarter, 25);

        result.put("startDate", startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        result.put("endDate", endDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

        return result;
    }

    // 测试方法
//    public static void main(String[] args) {
//        // 测试案例1: 2025-06-28 应归属Q3
//        LocalDate date1 = LocalDate.of(2025, 3, 25);
//        Map<String, LocalDate> result1 = calculateQuarterDateRange(date1);
//        System.out.println("日期 " + date1 + " 归属季度:");
//        System.out.println("开始日期: " + result1.get("startDate")); // 2025-06-26
//        System.out.println("结束日期: " + result1.get("endDate"));   // 2025-09-25
//
//        // 测试案例2: 2025-06-25 应归属Q2
//        LocalDate date2 = LocalDate.of(2025, 3, 25);
//        Map<String, LocalDate> result2 = calculateQuarterDateRange(date2);
//        System.out.println("\n日期 " + date2 + " 归属季度:");
//        System.out.println("开始日期: " + result2.get("startDate")); // 2025-03-26
//        System.out.println("结束日期: " + result2.get("endDate"));   // 2025-06-25
//
//        // 测试案例3: 2025-12-30 应归属下一年Q1
//        LocalDate date3 = LocalDate.of(2025, 12, 30);
//        Map<String, LocalDate> result3 = calculateQuarterDateRange(date3);
//        System.out.println("\n日期 " + date3 + " 归属季度:");
//        System.out.println("开始日期: " + result3.get("startDate")); // 2025-12-26
//        System.out.println("结束日期: " + result3.get("endDate"));   // 2026-03-25
//
//        // 测试案例3: 2025-12-30 应归属下一年Q1
//        LocalDate date4 = LocalDate.of(2025, 3, 26);
//        Map<String, LocalDate> result4 = calculateQuarterDateRange(date3);
//        System.out.println("\n日期 " + date4 + " 归属季度:");
//        System.out.println("开始日期: " + result4.get("startDate")); // 2025-12-26
//        System.out.println("结束日期: " + result4.get("endDate"));   // 2026-03-25
//    }

    public static Map<String, String> calculatePreviousQuarterRange(LocalDate inputDate) {
        Map<String, String> result = new HashMap<>();

        // 1. 先确定输入日期实际归属的季度（应用逻辑）
        int year = inputDate.getYear();
        int month = inputDate.getMonthValue();
        int day = inputDate.getDayOfMonth();
        int originalQuarter = (month - 1) / 3 + 1;
        boolean needAdjust = (day >= 26) && (month == 3 || month == 6 || month == 9 || month == 12);

        int adjustedQuarter;
        int adjustedYear;
        if (needAdjust) {
            if (originalQuarter == 4) {
                adjustedQuarter = 1;
                adjustedYear = year + 1;
            } else {
                adjustedQuarter = originalQuarter + 1;
                adjustedYear = year;
            }
        } else {
            adjustedQuarter = originalQuarter;
            adjustedYear = year;
        }

        // 2. 计算归属季度的上个季度
        int previousQuarter;
        int previousYear;
        if (adjustedQuarter == 1) {
            previousQuarter = 4;
            previousYear = adjustedYear - 1;
        } else {
            previousQuarter = adjustedQuarter - 1;
            previousYear = adjustedYear;
        }

        // 3. 计算上个季度的开始日期（上上个季度最后一个月的26号）
        LocalDate prevStartDate;
        if (previousQuarter == 1) {
            prevStartDate = LocalDate.of(previousYear - 1, 12, 26);
        } else {
            int lastMonthOfPrevPrevQuarter = (previousQuarter - 1) * 3;
            prevStartDate = LocalDate.of(previousYear, lastMonthOfPrevPrevQuarter, 26);
        }

        // 4. 计算上个季度的结束日期（上个季度最后一个月的25号）
        int lastMonthOfPreviousQuarter = previousQuarter * 3;
        LocalDate prevEndDate = LocalDate.of(previousYear, lastMonthOfPreviousQuarter, 25);

        result.put("startDate", prevStartDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        result.put("endDate", prevEndDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

        return result;
    }

    // 测试方法
    public static void main(String[] args) {
        // 测试案例1: 2025-06-28 归属Q3，上个季度是Q2
//        LocalDate date1 = LocalDate.of(2025, 3, 28);
//        Map<String, LocalDate> result1 = calculatePreviousQuarterRange(date1);
//        System.out.println("日期 " + date1 + " 归属季度的上个季度:");
//        System.out.println("开始日期: " + result1.get("prevStartDate")); // 2025-03-26
//        System.out.println("结束日期: " + result1.get("prevEndDate"));   // 2025-06-25
//
//        // 测试案例2: 2025-06-25 归属Q2，上个季度是Q1
//        LocalDate date2 = LocalDate.of(2025, 3, 25);
//        Map<String, LocalDate> result2 = calculatePreviousQuarterRange(date2);
//        System.out.println("\n日期 " + date2 + " 归属季度的上个季度:");
//        System.out.println("开始日期: " + result2.get("prevStartDate")); // 2024-12-26
//        System.out.println("结束日期: " + result2.get("prevEndDate"));   // 2025-03-25
//
//        // 测试案例3: 2025-12-30 归属2026-Q1，上个季度是2025-Q4
//        LocalDate date3 = LocalDate.of(2025, 12, 30);
//        Map<String, LocalDate> result3 = calculatePreviousQuarterRange(date3);
//        System.out.println("\n日期 " + date3 + " 归属季度的上个季度:");
//        System.out.println("开始日期: " + result3.get("prevStartDate")); // 2025-09-26
//        System.out.println("结束日期: " + result3.get("prevEndDate"));   // 2025-12-25
    }

}
